package com.ymh.service.impl;

import com.ymh.dao.OrderDao;
import com.ymh.domain.OrderDO;
import com.ymh.domain.OrderDTO;
import com.ymh.fegin.AccountFeign;
import com.ymh.feign.ProductFeign;

import com.ymh.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author: 13590
 * @date: 2020/10/26 21:12
 * @description:
 */
@Service
public class OrderServiceImpl implements OrderService {

  @Autowired
  private ProductFeign productFeign;
  @Autowired
  private AccountFeign accountFeign;
  @Autowired
  private OrderDao orderDao;

  @Override
  @GlobalTransactional(name = "TX_ORDER_CREATE")
  public void createOrder(OrderDTO orderDTO) {
    OrderDO orderDO = new OrderDO();
    BeanUtils.copyProperties(orderDTO, orderDO);
    //库存扣减
    productFeign.deduct(orderDTO.getProductCode(), orderDO.getCount());
    //账户余额扣减
    accountFeign.reduce(orderDTO.getAccountCode(), orderDO.getAmount());
    //本地存储Order
    this.saveOrder(orderDO);
  }


  @Transactional(rollbackFor = RuntimeException.class)
  void saveOrder(OrderDO orderDO) {
    orderDao.save(orderDO);
  }


}
